<?php
namespace app\api\controller;

use think\Db;


header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Max-Age:3600");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken,Token,ID");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS');


class Uplevel extends Check
{
    protected function _initialize(){
        parent::_initialize();
    }
    private $team_arr=[];
    private $team_level_user=[];
    private $num = 0;
    private $team_count = 0;
    private $up_user_id = 0;
    protected function team_arr($num = 20)
    {
        for ($i=0;$i<=$num;$i++){
            $this->team_arr[$i]['level'] = $i;
            $this->team_arr[$i]['count'] = 0;
        }
        return $this->team_arr;
    }
    protected function team_user($user_id = 0)
    {
        if (empty($this->team_arr)) {
            $this->team_arr();
        }
        $find_user = Db::name('user')->where('in_user_id',$user_id)->select();
        if(!empty($find_user)) {
            foreach ($find_user as $k => $v) {
                $this->team_arr[$v['level']]['count']++;
                $this->team_count++;
                $this->team_user($v['id']);
            }
        }
    }
    protected function team_level_user($user_id = 0 , $level = 0)
    {
        $find_user = Db::name('user')->where('in_user_id',$user_id)->field('id,level,image,username,mobile')->select();
        if(!empty($find_user)) {
            foreach ($find_user as $k => $v) {
                if($v['level']==$level){
                    $this->team_level_user[] = $v;
                }
                $this->team_level_user($v['id'],$level);
            }
        }
    }
    protected function level_info($level=0,$user_id = 0)
    {
        $user = Db::name('user')->where('in_user_id',$user_id)->select();
        if(!empty($user)) {
            foreach ($user as $k => $v) {
                if ($v['level'] >= ($level - 1)) {
                    $this->num++;
                }
//                if ($num >= 2) {
//                    break;
//                }
                $this->level_info($level,$v['id']);
            }
        }
        return $this->num;
    }
    protected function is_up_level()
    {
        $user = Db::name('user')->where('id',$this->uid)->find();
        if ($user['level']!=0&&$user['level']!=20) {
            $level_num = $this->level_info($user['level'], $user['id']);
            if($level_num>=2){
                return $level_num;
            }else{
                return false;
            }
        }else{
            if($user['level'] == 0){
                return true;
            }else{
                return false;
            }
        }
    }
    protected function find_up_user($user_id = 0,$level = 0)
    {
        for ($i = 0;$i<=$level;$i++){
            $user = Db::name('user')->where('id',$user_id)->find();
            if(empty($user['in_user_id'])){
                break;
            }
            $user_id = $user['in_user_id'];
        }
        return $user_id;
    }
    protected function is_up_user($up_user_id = 0,$level = 0,$type = false)
    {
        $up_user = Db::name('user')->where('id',$up_user_id)->find();
        if(empty($up_user['in_user_id'])){
            $this->up_user_id = $up_user_id;
            return $up_user_id;
        }
        if($up_user['status']!=1||($up_user['level']<=$level)){
            if($type) {
                $where = [
                    'user_id' => $this->uid,
                    'up_user_id' => $up_user_id,
                    'type' => 0,
                    'level' => $level,
                ];
                $r = Db::name('upgrade')->where($where)->find();
                if(!$r) {
                    $save = [
                        'user_id' => $this->uid,
                        'up_user_id' => $up_user_id,
                        'money' => $this->check_money($level),
                        'type' => 0,
                        'level' => $level,
                        'add_time' => time()
                    ];
                    Db::name('upgrade')->insertGetId($save);
                }else{
                    Db::name('upgrade')->where('id',$r)->update(['add_time'=>time()]);
                }
            }
            $up_user_id = $this->find_up_user($up_user_id,0);
            $this->is_up_user($up_user_id,$level,$type);
        }else{
            $this->up_user_id = $up_user_id;
            return $up_user_id;
        }
    }
    /*
     * 计算价格
     *
     * */
    protected function check_money($level = true)
    {
        $account_config = Db::name('system')->field('value')->where('name', 'account_config')->find();
        $account_config = unserialize($account_config['value']);
        $money = $account_config['money'] + rand(1,99)/100;
        if(!$level){
            $money = $money/2;
        }
        return sprintf("%.2f",$money);
    }
    public function is_upgrade()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            $r = $this->is_up_level();
            if ($r) {
                $song = Db::name('upgrade')->where(['user_id'=>$this->uid,'status'=>0])->find();
                if($song){
                    return $this->splash(0, '存在升级申请，不能申请升级');
                }

                $level = Db::name('user')->where('id',$this->uid)->value('level');
                $up_user_id = $this->find_up_user($this->uid,$level);
                $up_user_id = $this->is_up_user($up_user_id,$level);
                $in_user = Db::name('user')->where('id',$this->up_user_id)->field('id,username,mobile,wx,wx_code,level')->find();
                $money = $this->check_money($level);
                $in_user['up_money']= $level==0?$money - 4:$money;
                $send['up_user']=$in_user;
                if($level==0){
                    $pingtai = Db::name('system')->field('value')->where('name', 'account_config')->find();
                    $pingtai = unserialize($pingtai['value']);
                    unset($pingtai['money']);
                    $send['is_pingtai'] = 1;
                    $pingtai['pingtai_money'] = $level==0?$money + 4:$money;
                    $send['pingtai'] = $pingtai;
                }else{
                    $send['is_pingtai'] = 0;
                }
                return $this->splash(1, '可以升级',$send);
            } else {
                return $this->splash(0, '团队条件不满足，不能升级');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 接口，提交升级申请
     *
     * up_user_id  上级id
     *
     */
    public function upgrade()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['image']) || !isset($data['up_user_id'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $r = $this->is_up_level();
            if ($r) {
                $song = Db::name('upgrade')->where(['user_id'=>$this->uid,'status'=>0])->find();
                if($song){
                    return $this->splash(0, '存在升级申请，不能申请升级');
                }
                $level = Db::name('user')->where('id',$this->uid)->value('level');
                $up_user_id = $this->find_up_user($this->uid,$level);
                $up_user_id = $this->is_up_user($up_user_id,$level,true);
//                $in_user = Db::name('user')->where('id',$up_user_id)->field('id,username,mobile,wx,wx_code,zfb,zfb_code,level')->find();
                if($this->up_user_id!=$data['up_user_id']){
                    return $this->splash(0,'上级信息有误，退出重试');
                }
                $money = $this->check_money($level);
                $save = [
                    'user_id' => $this->uid,
                    'image' => implode(',',$data['image']),
                    'up_user_id' => $data['up_user_id'],
                    'money' => $money,
                    'up_money' => $level==0?$money - 4:$money,
                    'pingtai_money' => $level==0? $money + 4: 0,
                    'level' => $level,
                    'add_time' => time(),
                    'is_pingtai' => $level==0? 1 : 0,
                ];
                $r = Db::name('upgrade')->where(['user_id'=>$this->uid,'level'=>$level])->order('id desc')->find();
                if($r){
                    $update['status']=0;
                    $update['status_time'] = time();
                    $update['image'] = implode(',',$data['image']);
                    if($r['up_status']==2){
                        $update['up_status'] = 0;
                    }
                    if ($r['pingtai_status']==2){
                        $update['pingtai_status'] = 0;
                    }
                    $u = Db::name('upgrade')->where(['id'=>$r['id']])->update($update);
                }else {
                    $u = Db::name('upgrade')->insertGetId($save);
                }
                if($u){
                    return $this->splash(1, '申请成功');
                }else{
                    return $this->splash(0, '申请出错，请稍后重试');
                }
            } else {
                return $this->splash(0, '团队条件不满足，不能升级');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    public function my_team()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            $this->team_user($this->uid);
            if ($this->team_arr) {
                $leiji = Db::name('upgrade')->where(['up_user_id'=>$this->uid,'type'=>1,'status'=>1])->count('money');
                $loudan = Db::name('upgrade')->where(['up_user_id'=>$this->uid,'type'=>0])->count('money');
                $send = [
                    'leiji'=>$leiji,
                    'loudan'=>$loudan,
                    'team_count'=>$this->team_count,
                    'team_zero_up'=>$this->team_count - $this->team_arr[0]['count'],
                    'team'=>$this->team_arr,
                ];
                return $this->splash(1, '获取成功',$send);
            } else {
                return $this->splash(0, '没有数据');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    public function my_team_level()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['level'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $this->team_level_user($this->uid,$data['level']);
            if ($this->team_level_user) {
                $send = [
                    'img_url'=>'http://' . $_SERVER['SERVER_NAME'].'/public/',
                    'team_level'=>$this->team_level_user,
                ];
                return $this->splash(1, '获取成功',$send);
            } else {
                return $this->splash(0, '没有数据');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 升级申请、历史页面
     * type 0 正在 1 历史
     */
    public function upgrade_my()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['type'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $where['user_id']=['eq',$this->uid];
            $where['type']=['eq',1];
            if($data['type']==0){
                $where['status']=['eq',0];
            }else{
                $where['status']=['neq',0];
            }
            $list = Db::name('upgrade')->where($where)->field('up_money,pingtai_money',true)->select();
            if ($list) {
                $pingtai = Db::name('system')->field('value')->where('name', 'account_config')->find();
                $pingtai = unserialize($pingtai['value']);
                unset($pingtai['money']);
                foreach ($list as $k=>$v){
                    $list[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                    if ($v['is_pingtai']==1){
                        $list[$k]['pingtai'] = $pingtai;
                    }
                    $list[$k]['up_user'] = Db::name('user')->where('id',$v['up_user_id'])->field('id,username,mobile,wx,wx_code,level')->find();
                }
                $send = [
                    'img_url'=>'http://' . $_SERVER['SERVER_NAME'].'/public/',
                    'list'=>$list,
                ];
                return $this->splash(1, '获取成功',$send);
            } else {
                return $this->splash(0, '没有数据');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 我的订单 列表
     * type 0 待审核 1 已审核
     * */
    public function upgrade_team_list()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            $pageno = $this->request->param('pageno',1);
            $pageindex = $this->request->param('pageindex',10);
            if (!$this->uid || !isset($data['type'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $where['up_user_id']=['eq',$this->uid];
            $where['type']=['eq',1];
            if($data['type']==0){
                $where['status']=['eq',0];
            }else{
                $where['status']=['neq',0];
            }
            $list = Db::name('upgrade')->where($where)->page($pageno,$pageindex)->field('up_money,pingtai_money',true)->select();

            if ($list) {
                foreach ($list as $k=>$v){
                    $list[$k]['user'] = Db::name('user')->where(['id'=>$v['user_id']])->field('id,username,wx,mobile')->find();
                    $list[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                }
                $send = [
                    'img_url'=>'http://' . $_SERVER['SERVER_NAME'].'/public/',
                    'list'=>$list,
                ];
                return $this->splash(1, '获取成功',$send);
            } else {
                return $this->splash(0, '没有数据');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 我的订单 详情
     * type 0 待审核 1 已审核
     * */
    public function upgrade_team_info()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['id'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $where['up_user_id']=['eq',$this->uid];
            $where['type']=['eq',1];
            $where['id']=['eq',$data['id']];

            $info = Db::name('upgrade')->where($where)->field('up_money,pingtai_money',true)->find();

            if ($info) {
                $info['user'] = Db::name('user')->where(['id'=>$info['user_id']])->field('id,username,wx,mobile')->find();
                $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
                $info['image'] = explode(',',$info['image']);
                $send = [
                    'img_url'=>'http://' . $_SERVER['SERVER_NAME'].'/public/',
                    'info'=>$info,
                ];
                return $this->splash(1, '获取成功',$send);
            } else {
                return $this->splash(0, '没有数据');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
    /*
     * 审核
     * type 0 不通过 1 通过
     * */
    public function upgrade_status()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!$this->uid || !isset($data['type']) || !isset($data['id'])) {
                return $this->splash(0, '信息不完整，请重试');
            }
            $info = Db::name('upgrade')->where(['id'=>$data['id']])->find();
            $is_upgrade = 0;

            $save['up_time'] = time();
            if ($data['type'] == 0) {
                $save['up_status'] = 2;
                $save['status_time'] = time();
                $save['status'] = 2;
            } elseif ($data['type'] == 1) {
                $save['up_status'] = 1;
                if ($info['is_pingtai'] == 0){
                    $is_upgrade = 1;
                    $save['status_time'] = time();
                    $save['status'] = 1;
                }else{
                    if($info['pingtai_status'] == 1){
                        $is_upgrade = 1;
                        $save['status_time'] = time();
                        $save['status'] = 1;
                    }elseif($info['pingtai_status'] == 0){
                    }elseif($info['pingtai_status'] == 2){
                        $save['status_time'] = time();
                        $save['status'] = 2;
                    }
                }
            } else {
                return $this->splash(0, '错误');
            }

            $r = Db::name('upgrade')->where(['id'=>$data['id']])->update($save);
            if ($r) {
                if($is_upgrade==1){
                    $level = $info['level'] +1;
                    Db::name('user')->where(['id'=>$info['user_id']])->update(['level'=>$level]);
                }
                return $this->splash(1, '审核成功');
            } else {
                return $this->splash(0, '没有数据');
            }
        }else{
            return $this->splash(0, '请求错误');
        }
    }
}
